package own.stu.inter.loadbalance.ping;

import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import own.stu.inter.loadbalance.httpclient.AsyncHttpHelper;
import own.stu.inter.loadbalance.server.ServerInstance;

import java.util.concurrent.CompletableFuture;

public class PingUrl implements IPing {

    protected static Logger logger = LoggerFactory.getLogger(PingUrl.class);

    String pingAppendString = "";

    String expectedContent = null;

    public PingUrl() {
    }

    public PingUrl(String pingAppendString) {
        this.pingAppendString = pingAppendString != null ? pingAppendString : "";
    }

    public void setPingAppendString(String pingAppendString) {
        this.pingAppendString = pingAppendString != null ? pingAppendString : "";
    }

    public String getPingAppendString() {
        return pingAppendString;
    }

    public String getExpectedContent() {
        return expectedContent;
    }

    /**
     * 异常信息，用来检查服务是否存活的内容
     */
    public void setExpectedContent(String expectedContent) {
        this.expectedContent = expectedContent;
    }

    public boolean isAlive(ServerInstance instance) {
        String urlStr = "http://" + instance.getId();
        urlStr += getPingAppendString();

        boolean isAlive = false;

        String content = null;
        try {

            CompletableFuture<Response> responseFuture = AsyncHttpHelper.getInstance().executeRequest(
                    new RequestBuilder().setUrl(urlStr).build());
            Response response = responseFuture.get();

            content = response.getResponseBody();
            isAlive = response.getStatusCode() == 200;
            if (getExpectedContent() != null) {
                logger.debug("content:" + content);
                if (content == null || !content.equals(getExpectedContent())) {
                    isAlive = false;
                }
            }
        } catch (Exception e) {
            logger.error("pingUrl ping {} isAlive error", instance, e);
        }

        return isAlive;
    }
}
